<template>
    <div class="clue-container">
      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="客户姓名">
          <el-input v-model="searchForm.name" placeholder="请输入客户姓名" size="small" />
        </el-form-item>
        <el-form-item label="客户手机">
          <el-input v-model="searchForm.phone" placeholder="请输入客户手机号" size="small" />
        </el-form-item>
        <el-form-item label="归属人">
          <el-input v-model="searchForm.owner" placeholder="请输入线索归属人" size="small" />
        </el-form-item>
        <el-form-item label="渠道来源">
          <el-select v-model="searchForm.channelId" placeholder="渠道来源" size="small" clearable>
            <el-option v-for="item in channelOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="线索状态">
          <el-select v-model="searchForm.status" placeholder="线索状态" size="small" clearable>
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="handleSearch">搜索</el-button>
          <el-button size="small" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
  
      <!-- 操作按钮 -->
      <div style="margin: 10px 0;padding: 0 10px;">
        <el-button type="primary" size="small" @click="openAddDialog">新增</el-button>
        <el-button type="success" size="small" @click="onEdit" :disabled="!selectedRow">修改</el-button>
        <el-button type="danger" size="small">删除</el-button>
        <el-button type="warning" size="small" @click="handleExport">导出</el-button>
      </div>
  
      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        stripe
        style="width: 100%;padding: 0 10px;"
        @selection-change="handleSelectionChange"
        :row-key="row => row.clueId"
        ref="clueTable"
      >
        <el-table-column type="selection" width="50" :selectable="selectableOnlyOne" />
        <el-table-column prop="name" label="客户姓名" width="200" />
        <el-table-column prop="phone" label="手机号" width="200" />
        <el-table-column prop="owner" label="商机归属" width="150" />
        <el-table-column prop="createTime" label="创建时间" width="200" align="center">
          <template #default="scope">
            <span class="gray-time">{{ (scope.row.createTime || '').replace('T', ' ') }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="线索状态" width="82">
          <template #default="scope">
            <el-tag
              type="info"
              style="background-color: #e6f7ff; color: #409EFF; border: none;padding: 0 10px;"
              effect="light"
              v-if="scope.row.status === 1 || scope.row.status === '已分配'"
            >
              已分配
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="nextTime" label="下次跟进时间" width="200" align="center">
          <template #default="scope">
            <span class="gray-time">{{ (scope.row.nextTime || '').replace('T', ' ') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-link type="primary" @click="onView(scope.row)">
              <el-icon style="vertical-align: middle;"><View /></el-icon>
              <span style="margin-left: 2px;vertical-align: middle;">查看</span>
            </el-link>
            <el-link type="success" @click="onAssign(scope.row)">
              <el-icon style="margin-left: 8px;vertical-align: middle;"><Pointer /></el-icon>
              <span style="margin-left: 2px;vertical-align: middle;">分配</span>
            </el-link>
            <el-tag v-if="scope.row.type !== undefined" size="small" style="margin-left: 6px;vertical-align: middle;">
              {{ scope.row.type === 0 ? '普通' : scope.row.type === 1 ? '重要' : '未知' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页 -->
      <div style="display: flex;justify-content: center;align-items: center;margin-top: 10px;">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
  
      <!-- 分配弹窗 -->
      <el-dialog v-model="assignDialogVisible" title="分配线索" width="600px">
        <el-form :model="assignForm" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="归属部门" prop="deptId" required>
                <el-tree-select
                  v-model="assignForm.deptId"
                  :data="deptOptions"
                  :props="{ label: 'label', value: 'id', children: 'children' }"
                  placeholder="请选择归属部门"
                  check-strictly
                  style="width: 100%;"
                  @change="handleDeptChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="分配给" prop="userId" required>
                <el-select v-model="assignForm.userId" placeholder="选择用户" :disabled="!userOptions.length">
                  <el-option v-for="user in userOptions" :key="user.userId" :label="user.nickName" :value="user.userId" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <el-button @click="assignDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAssignSubmit">确定</el-button>
        </template>
      </el-dialog>
  
      <!-- 新增线索弹窗 -->
      <el-dialog v-model="showAddDialog" :title="isEdit ? '编辑线索' : '添加线索'" width="800px">
        <el-form :model="addForm" label-width="90px" :rules="addRules" ref="addFormRef" class="add-form">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="手机号" prop="phone" required>
                <el-input v-model="addForm.phone" placeholder="请输入手机号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户姓名" prop="name" required>
                <el-input v-model="addForm.name" placeholder="请输入客户姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="渠道来源" prop="channelId">
                <el-select v-model="addForm.channelId" placeholder="渠道来源" @change="handleAddChannelChange">
                  <el-option v-for="item in channelOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="活动信息" prop="activityId">
                <el-select v-model="addForm.activityId" placeholder="活动信息">
                  <el-option v-for="item in activityOptions" :key="item.value" :label="item.name" :value="item.activityId" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="客户性别" prop="gender">
                <el-radio-group v-model="addForm.gender">
                  <el-radio :label="0">男</el-radio>
                  <el-radio :label="1">女</el-radio>
                  <el-radio :label="2">未知</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="微信号" prop="weixin">
                <el-input v-model="addForm.weixin" placeholder="请输入微信号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="QQ号码" prop="qq">
                <el-input v-model="addForm.qq" placeholder="请输入QQ号码" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="客户年龄" prop="age">
                <el-input-number v-model="addForm.age" :min="0" :max="120" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="isEdit ? handleUpdateSubmit() : handleAddSubmit()">{{ isEdit ? '更新' : '确定' }}</el-button>
        </template>
      </el-dialog>
      </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue'
  import request from '@/utils/request'
  import { ElMessage } from 'element-plus'
  import { View, Pointer } from '@element-plus/icons-vue'
  import { download } from '@/utils/request'
  import { useRouter } from 'vue-router'
  
  const channelOptions = [
    { value: 1, label: '抖音短视频' },
    { value: 2, label: '线下地推' },
    { value: 3, label: '公众号推广' },
    { value: 4, label: '小程序推广' }
  ]
  const statusOptions = [
    { value: 1, label: '已分配' },
    // 可根据实际接口补充更多状态
  ]
  
  const searchForm = ref({
    name: '',
    phone: '',
    owner: '',
    channelId: undefined,
    status: undefined
  })
  
  const tableData = ref([])
  const total = ref(0)
  const pageSize = ref(10)
  const currentPage = ref(1)
  const loading = ref(false)
  
  // 分配弹窗相关
  const assignDialogVisible = ref(false)
  const assignForm = ref({ deptId: '', userId: '' })
  const deptOptions = ref([])
  const userOptions = ref([])
  let currentAssignRow = null
  
  // 新增线索相关
  const showAddDialog = ref(false)
  const addFormRef = ref()
  const addForm = ref({
    phone: '',
    name: '',
    channelId: undefined,
    activityId: undefined,
    gender: 0,
    age: undefined,
    weixin: '',
    qq: ''
  })
  const addRules = {
    phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
    name: [{ required: true, message: '请输入客户姓名', trigger: 'blur' }]
  }
  const activityOptions = ref([])
  const isEdit = ref(false)
  const editId = ref(null)
  const selectedRow = ref(null)
  const clueTable = ref()
  const router = useRouter()
  
  function fetchData() {
    loading.value = true
    request({
      url: '/tienchin/business/list',
      method: 'get',
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        name: searchForm.value.name,
        phone: searchForm.value.phone,
        owner: searchForm.value.owner,
        channelId: searchForm.value.channelId,
        status: searchForm.value.status
      }
    }).then(res => {
      tableData.value = res.rows || []
      total.value = res.total || 0
    }).finally(() => {
      loading.value = false
    })
  }
  
  function handleSearch() {
    currentPage.value = 1
    fetchData()
  }
  function handleReset() {
    searchForm.value = { name: '', phone: '', owner: '', channelId: undefined, status: undefined }
    currentPage.value = 1
    fetchData()
  }
  function handleSizeChange(val) {
    pageSize.value = val
    currentPage.value = 1
    fetchData()
  }
  function handlePageChange(val) {
    currentPage.value = val
    fetchData()
  }
  
  function onView(row) {
    // 跳转到详情页，传递id
    router.push(`/business/details/index/${row.businessId}/view`)
  }
  function onAssign(row) {
    currentAssignRow = row
    assignForm.value = { deptId: '', userId: '' }
    userOptions.value = []
    assignDialogVisible.value = true
    // 获取部门树
    request({ url: '/system/dept/treeselect', method: 'get' }).then(res => {
      deptOptions.value = res.data || []
    })
  }
  function handleDeptChange(deptId) {
    assignForm.value.userId = ''
    userOptions.value = []
    if (!deptId) return
    request({ url: `/tienchin/clue/users/${deptId}`, method: 'get' }).then(res => {
      userOptions.value = res.data || []
    })
  }
  function handleAssignSubmit() {
    if (!assignForm.value.deptId || !assignForm.value.userId) {
      ElMessage.error('请选择归属部门和分配用户')
      return
    }
    // 获取选中的用户对象
    const user = userOptions.value.find(u => u.userId === assignForm.value.userId)
    if (!user) {
      ElMessage.error('请选择有效的分配用户')
      return
    }
    const postData = {
      assignId: currentAssignRow.clueId,
      departmentId: assignForm.value.deptId,
      deptId: assignForm.value.deptId,
      nickName: user.nickName,
      type: 0,
      userId: user.userId,
      userName: user.userName
    }
    request({
      url: '/tienchin/assignment',
      method: 'post',
      data: postData
    }).then(() => {
      ElMessage.success('分配成功')
      assignDialogVisible.value = false
      fetchData()
    })
  }
  
  function openAddDialog() {
    isEdit.value = false
    editId.value = null
    addForm.value = {
      phone: '',
      name: '',
      channelId: undefined,
      activityId: undefined,
      gender: 0,
      age: undefined,
      weixin: '',
      qq: ''
    }
    activityOptions.value = []
    showAddDialog.value = true
  }
  
  function onEdit() {
    // 这里只支持单选编辑
    const selection = getSelection()
    if (!selection) {
      ElMessage.warning('请先选择一条要编辑的数据')
      return
    }
    isEdit.value = true
    editId.value = selection.clueId
    // 获取详情
    request({ url: `/tienchin/clue/summary/${editId.value}`, method: 'get' }).then(res => {
      const data = res.data || {}
      // 先设置渠道来源
      addForm.value = {
        phone: data.phone,
        name: data.name,
        channelId: data.channelId,
        activityId: undefined, // 先不设置，等活动信息加载后再设置
        gender: data.gender,
        age: data.age,
        weixin: data.weixin,
        qq: data.qq
      }
      // 先加载活动信息
      handleAddChannelChange(data.channelId, data.activityId)
      showAddDialog.value = true
    })
  }
  
  function handleAddChannelChange(channelId, activityIdToSet) {
    addForm.value.activityId = undefined
    activityOptions.value = []
    if (!channelId) return
    request({ url: `/tienchin/clue/activity/${channelId}`, method: 'get' }).then(res => {
      activityOptions.value = res.data || []
      // 如果是编辑，回显activityId
      if (activityIdToSet) {
        addForm.value.activityId = activityIdToSet
      }
    })
  }
  
  function handleAddSubmit() {
    addFormRef.value.validate(valid => {
      if (!valid) return
      request({
        url: '/tienchin/business',
        method: 'post',
        data: addForm.value
      }).then(() => {
        ElMessage.success('添加成功')
        showAddDialog.value = false
        fetchData()
      })
    })
  }
  
  function handleUpdateSubmit() {
    addFormRef.value.validate(valid => {
      if (!valid) return
      request({
        url: '/tienchin/business',
        method: 'put',
        data: { ...addForm.value, clueId: editId.value }
      }).then(() => {
        ElMessage.success('更新成功')
        showAddDialog.value = false
        fetchData()
      })
    })
  }
  
  // 获取表格选中行（单选）
  function getSelection() {
    // 这里假设el-table有ref="clueTable"
    // 你可以根据实际表格多选实现调整
    // 或直接用tableData.value.find(...)
    const table = document.querySelector('.el-table__body')
    if (!table) return null
    // 这里只做演示，建议用el-table的selection-change事件维护选中行
    // 你可以用el-table的ref和getSelectionRows
    return selectedRow.value
  }
  
  function handleSelectionChange(selection) {
    if (selection.length === 1) {
      selectedRow.value = selection[0]
    } else {
      selectedRow.value = null
    }
  }
  function selectableOnlyOne(row, index) {
    // 只允许单选，已选后其它不可选
    if (clueTable.value) {
      const selected = clueTable.value.getSelectionRows()
      return selected.length === 0 || selected[0].clueId === row.clueId
    }
    return true
  }
  
  function handleExport() {
    download('/tienchin/course/export', {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      // 可根据需要添加更多参数
    }, '商机数据.xlsx')
  }
  
  onMounted(() => {
    fetchData()
  })
  </script>
  
  <style lang="scss" scoped>
  * {
    margin: 0;
    padding: 0;
  }
  .search-form {
    margin-bottom: 10px;
    padding:0 10px;
  }
  .gray-time {
    color: #909399;
    font-size: 14px;
  }
  .clue-container {
    padding:10px;
  }
  .el-button, .el-link {
    font-size: 12px !important;
  }
  .el-button {
    height: 25px !important;
    padding: 0 15px !important;
  }
  .add-form .el-form-item {
    margin-bottom: 18px;
  }
  </style>